<template>
  <div>
    <a-drawer
      v-model:visible="visible"
      class="custom-class"
      :title="title"
      placement="right"
      @close="modalClose.close"
      @after-visible-change="afterVisibleChange"
    >
      <div>
        <a-form :label-col="{ span: 12 }" :wrapper-col="{ span: 24 }" label-align="left" :layout="'vertical'">
          <a-form-item label="所属应用/客户端" v-bind="validateInfos.appName">
            <cascader
              v-if="modelRef.clientName || isEdit === 'new'"
              :app-type-list="appTypeListTra"
              :width="'313px'"
              :app-type-text="modelRef.clientName"
              placeholder="请选择所属客户端"
              :is-disable="title === '详情'"
              @edit-change="appTypeValeChange"
            ></cascader>
          </a-form-item>
          <a-form-item label="选择功能" v-bind="validateInfos.functionName">
            <a-input
              v-model:value="modelRef.functionName"
              :disabled="isDetl"
              placeholder="请选择功能"
              @click="inpCli"
            />
            <div v-if="isShowTree" class="my-edit-tree">
              <div style="height: 30px; margin: 10px; text-align: end; border-bottom: 1px solid #d9d9d9">
                <CloseOutlined @click="inpClose" />
              </div>
              <div class="my-edit-tree-sub">
                <tree @tree-node-selected="treeNodeSelected"></tree>
              </div>
            </div>
          </a-form-item>
          <a-form-item label="上级菜单">
            <a-input :disabled="true" :value="upperRol.name" />
          </a-form-item>
          <a-form-item label="名称" v-bind="validateInfos.name">
            <a-input v-model:value="modelRef.name" :disabled="isDetl" placeholder="请输入菜单名称" />
          </a-form-item>
          <a-form-item label="图标">
            <a-input v-model:value="modelRef.icon" :disabled="isDetl" placeholder="请输入菜单图标的链接" />
          </a-form-item>
          <a-form-item label="排序">
            <a-input-number v-model:value="modelRef.sort" :min="0" :precision="0" :disabled="isDetl" />
          </a-form-item>
          <a-form-item label="是否启用">
            <a-switch v-model:checked="modelRef.status1" :disabled="isDetl" @change="onchangeSwitch" />
          </a-form-item>
          <a-form-item label="是否隐藏">
            <a-switch v-model:checked="modelRef.hidden" :disabled="isDetl" />
          </a-form-item>
          <a-form-item label="组件名称" v-bind="validateInfos.componentName">
            <a-input v-model:value="modelRef.componentName" :disabled="isDetl" placeholder="请输入组件英文名称" />
          </a-form-item>
          <a-form-item label="类型">
            <a-select ref="select" v-model:value="modelRef.type" :disabled="title === '详情'">
              <a-select-option v-for="item in typeList" :key="item.key" :value="item.key">
                {{ item.label }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="路径">
            <a-input v-model:value="modelRef.path" :disabled="isDetl" placeholder="请输入菜单路径" />
          </a-form-item>
          <a-form-item label="重定向路径">
            <a-input v-model:value="modelRef.redirect" :disabled="isDetl" placeholder="请输入重定向路径" />
          </a-form-item>
          <a-form-item label="备注" v-bind="validateInfos.remark">
            <a-textarea
              v-model:value="modelRef.remark"
              placeholder="备注"
              :disabled="isDetl"
              :auto-size="{ minRows: 2, maxRows: 2 }"
            />
          </a-form-item>
        </a-form>
      </div>
      <template #footer>
        <div style="display: flex; justify-content: left">
          <div v-show="!isDetl">
            <a-button type="primary" @click="onSubmit">{{ isDetl ? '关闭' : '确定' }}</a-button>
          </div>
          <div style="margin-left: 10px">
            <a-button @click="cancal">{{ isDetl ? '关闭' : '取消' }}</a-button>
          </div>
        </div>
      </template>
    </a-drawer>
    <a-modal v-model:visible="modalClose.modalVisible" title="关闭" @ok="modalClose.modalHandleOk">
      <span>数据未保存,确认关闭吗?</span>
    </a-modal>
  </div>
</template>
<script>
import { defineComponent, toRaw, ref, watch, defineEmits, toRefs, onMounted, reactive, nextTick } from 'vue'
import { CloseOutlined } from '@ant-design/icons-vue'
import { Form } from 'ant-design-vue'
import exp from '@/utils/regular'
const useForm = Form.useForm
import factory from '../factory'
//使用功能池的树, 选择功能池的项
import tree from '@/views/func-manag/func-aggr/components/tree'
import cascader from './cascader'

export default defineComponent({
  components: { tree, CloseOutlined, cascader },
  props: {
    isShowEdit: { type: Boolean, default: false },
    isEdit: { type: Number, default: 0 },
    currentItemId: { type: String, default: '' },
    typeList: { type: Array, default: () => [] },
    appTypeListTra: { type: Array, default: () => [] },
    upperRol: {
      type: Object,
      default: () => {
        return {}
      },
    },
  },
  emits: ['closeEdit', 'deletSuccess', 'editSuccess', 'createSuccess', 'updateSuccess'],
  setup(props, ctx) {
    const { isShowEdit, isEdit, currentItemId, upperRol } = toRefs(props)
    const modelRef = reactive({
      appKey: '',
      appName: '', //所属应用
      clientKey: '',
      clientName: '', //所属客户端
      functionId: '',
      functionName: '', //选择功能
      id: '',
      name: '',
      parentId: '',
      sort: '',
      alias: '',
      brandCodes: '',
      clientPath: '',
      code: '',
      componentName: '',
      createTime: '',
      icon: '',
      isCommon: '',
      isGlobal: '',
      keepAlive: '',
      level: '',
      linkTarget: '',
      modifyTime: '',
      path: '',
      remark: '',
      status: 'ENABLED',
      type: '菜单',
      url: '',
      hidden: false,
      status1: true,
      redirect: '',
    })
    const rulesRef = reactive({
      name: [
        {
          required: true,
          message: '请输入名称',
        },
        {
          pattern: exp.name.pattern,
          message: exp.name.message,
        },
        {
          max: 25,
          message: '最多输入25个字符',
        },
      ],
      appName: [
        {
          required: true,
          message: '请选择客户端',
        },
      ],
      functionName: [
        {
          required: true,
          message: '请选择功能',
        },
      ],
      remark: [
        {
          max: 127,
          message: '最多输入127个字符',
        },
      ],
      componentName: [
        {
          pattern: exp.key.pattern,
          message: exp.key.message,
        },
      ],
    })
    const { validate, validateInfos } = useForm(modelRef, rulesRef, {
      //表单验证的输出: 字段 值 提示
      onValidate: (...args) => {
        console.log('表单验证的输出: 字段 值 提示', ...args)
      },
    })

    //==保存==============================
    const onSubmit = () => {
      validate()
        .then(() => {
          //表单验证无误后执行
          save()
        })
        .catch((err) => {
          console.log('error', err)
        })
    }
    const save = () => {
      let post = { ...modelRef, parentId: upperRol.value.id }
      if (isEdit.value === 'new') {
        //新增
        factory.create(post).then((res) => {
          visible.value = false
          ctx.emit('createSuccess', modelRef.value)
          ctx.emit('closeEdit', false)
        })
      } else if (isEdit.value === 'edit') {
        //编辑
        factory.update(post).then((res) => {
          visible.value = false
          ctx.emit('updateSuccess', modelRef)
          ctx.emit('closeEdit', false)
        })
      }
    }

    //== 监视组件显示 =================================
    const visible = ref(false)
    const cancal = () => {
      modalClose.close()
    }
    const title = ref('')
    const isDetl = ref(false)
    watch(isShowEdit, (newValue, oldValue) => {
      if (newValue) {
        visible.value = true
        switch (isEdit.value) {
          case 'new':
            title.value = '新增'
            break
          case 'edit':
            title.value = '编辑'
            break
          case 'show':
            title.value = '详情'
            isDetl.value = true
            break
        }
        if (title.value !== '新增') {
          factory.getEditDetail(currentItemId.value).then((res) => {
            for (let key in res.data) {
              modelRef[key] = res.data[key]
            }
            modelRef.status1 = modelRef.status === 'ENABLED' ? true : false
            //备份数据
            modalClose.backupData = JSON.stringify(modelRef)
          })
        } else {
          //备份数据
          modalClose.backupData = JSON.stringify(modelRef)
        }
      }
    })
    watch(visible, (newValue, oldValue) => {
      if (!newValue) {
        ctx.emit('closeEdit', false)
      }
    })

    //==类型选择===========================
    const appTypeValeChange = (obj) => {
      modelRef.appKey = obj[1].appKey
      modelRef.appName = obj[1].name
      modelRef.clientKey = obj[2].clientKey
      modelRef.clientName = obj[2].name
    }

    //==树选择===========
    const isShowTree = ref(false)
    const inpCli = () => {
      isShowTree.value = !isShowTree.value
    }
    const inpClose = () => {
      isShowTree.value = false
    }
    const treeNodeSelected = (node) => {
      modelRef.functionId = node.id
      modelRef.functionName = node.name
      modelRef.name = node.name
      factory.getTreeNodeDetail(node.id).then((res) => {
        modelRef.code = res.data.code
        modelRef.path = res.data.path
        modelRef.sort = res.data.sort
        modelRef.icon = res.data.icon
        modelRef.componentName = res.data.componentName
      })
      isShowTree.value = false
    }
    //==是否启用=================
    const onchangeSwitch = (val) => {
      if (val) {
        modelRef.status = 'ENABLED'
      } else {
        modelRef.status = 'DISABLED'
      }
    }

    //==确认关闭对话框======================
    const modalClose = reactive({
      backupData: '',
      close: (e) => {
        if (JSON.stringify(modelRef) !== modalClose.backupData) {
          visible.value = true
          modalClose.modalVisible = true
          return
        }
        visible.value = false
      },
      modalVisible: false,
      modalHandleOk: () => {
        visible.value = false
      },
    })
    return {
      visible,
      onSubmit,
      title,
      cancal,
      validateInfos,
      modelRef,
      appTypeValeChange,
      isDetl,
      treeNodeSelected,
      isShowTree,
      inpCli,
      inpClose,
      modalClose,
      onchangeSwitch,
    }
  },
})
</script>
<style scoped lang="less">
.my-edit-tree {
  position: absolute;
  top: 40px;
  left: 0;
  z-index: 1;
  width: 330px;
  height: 497px;
  background-color: white;
  border: 1px solid black;
  //display: flex;
  .my-edit-tree-sub {
    width: 328px;
    height: 497px;
  }
}
</style>
